<!--
 * @Author: yy 2801140091@qq.com
 * @Date: 2022-09-07 16:06:19
 * @LastEditors: yy 2801140091@qq.com
 * @LastEditTime: 2022-09-07 16:20:07
 * @FilePath: \wh2212二阶段\day23\课堂代码\html\11省+市.html
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
-->
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>

    <select name="" id="sheng">
        <!-- <option value="">湖北省</option> -->
    </select>

    <select name="" id="city">
        <option value="">请选择</option>
    </select>

    <script>

        // 
        const oPro = document.querySelector('#sheng');
        const oCity = document.querySelector('#city');



        // 请求数据
        const xhr = new XMLHttpRequest();
        xhr.open('get', '../data/city.json', true);
        xhr.send();
        xhr.onreadystatechange = function () {
            if (xhr.readyState === 4 && xhr.status === 200) {
                let data = xhr.responseText;

                data = JSON.parse(data);
                console.log(data);


                // 显示省份
                let html = '<option value="请选择">请选择</option>';
                data.forEach(v => {
                    const { province } = v;
                    html += `<option value="${province}">${province}</option>`;
                })
                oPro.innerHTML = html;

                // 省份发生改变
                oPro.onchange = function () {
                    // 获取省份
                    const pro = oPro.value;
                    console.log(pro);
                    // 判断省份  --- 有可能没有选择
                    if (pro === '请选择') {
                        oCity.innerHTML = '<option value="请选择">请选择</option>';
                        return;
                    }
                    // 找到省份相关的数据    [{province:"" , children:[]}]
                    const cityArr = data.filter(v => v.province === pro)[0].children;
                    console.log(cityArr);
                    // 显示市
                    let html = '<option value="请选择">请选择</option>';
                    cityArr.forEach(v => {
                        const { city } = v;
                        html += `<option value="${city}">${city}</option>`;
                    })
                    oCity.innerHTML = html;
                    
                }
            }
        }

    </script>


</body>

</html>